<template>
  <div class="final-result-container isShowPay">
    <!-- 结果头部 - 渐变背景 -->
    <div class="showPay">
      <div class="result-header-card">
        <h1 class="result-title">{{ reportNotUnLockData.title }}</h1>
        <p class="result-description" v-html="reportNotUnLockData.content"></p>
      </div>
    </div>

    <div class="loading-container">
      <div class="pay">
        <img class="pay-img" src="../assets/images/pay_bg.webp" alt="" />
        <!-- 倒计时 -->
        <div class="time">
          <span>End in</span>
          <!-- 分钟 -->
          <div class="time-box">{{ minutes.toString().padStart(2, '0') }}</div>
          <i class="gap">:</i>
          <!-- 秒 -->
          <div class="time-box">{{ seconds.toString().padStart(2, '0') }}</div>
        </div>
        <div class="text">Your Personalized Emotional Attachment Report is Ready</div>
        <div class="price price1">${{ reportNotUnLockData.originPrice }}</div>
        <div class="price price2">${{ reportNotUnLockData.originPrice }}</div>
        <div class="price-limit">
          <div class="num">${{ reportNotUnLockData.discountPrice }}</div>
          <div class="tip">LIMITED TIME OFFER</div>
        </div>
      </div>
      <div class="btn" :class="{ 'is-disabled': isDisabled }" @click="toReport">
        <span v-if="!isLoading">Unlock the full report now</span>
        <svg v-else class="btn-loader-svg" viewBox="0 0 24 24">
          <circle class="btn-loader-circle" cx="12" cy="12" r="10" fill="none" stroke-width="2"></circle>
        </svg>
      </div>
    </div>

    <!-- 支付失败 请重试 -->
    <transition name="fade">
      <div class="payment-fail-dialog" v-if="type === 'FAIL_URL'">
        <div class="dialog-content">
          <div class="dialog-message">Payment failed, please try again</div>
          <button class="dialog-button" @click="closeFailDialog">Confirm</button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import api from '@/utils/api'
import { initializeAirwallex } from '@/utils/airwallex'
export default {
  name: 'Result',
  data() {
    let qurey = this.$route.query
    return {
      type: qurey.type || '',
      orderId: qurey.orderId || '',
      uid: qurey.uid || localStorage.getItem('uid'),
      loading: true,
      minutes: 0,
      seconds: 0,
      countdownTimer: null,
      reportNotUnLockData: {},
      isDisabled: false,
      isLoading: false,
      webUrl: window.location.origin,
    }
  },
  computed: {},

  created() {
    this.getEndCopywriting()
    ta.track('test_pay_show', { report_id: this.uid })
    if (this.type === 'FAIL_URL') {
      ta.track('test_pay_failed', { order_id: this.orderId, report_id: this.uid })
    }
  },
  mounted() {},
  methods: {
    // 获取页面数据
    getEndCopywriting() {
      api
        .getEndCopywritingApi({
          reportId: 1,
        })
        .then((res) => {
          // console.log(res)
          if (res.code == 200) {
            if (!res.data.unlock) {
              this.reportNotUnLockData = res.data.reportNotUnLock
              this.minutes = this.reportNotUnLockData.countdownDuration || 5
            } else {
              // this.toReport()
              this.$router.replace({
                path: 'report',
                query: {
                  uid: this.uid,
                },
              })
            }
          }
        })
    },

    // 模拟支付 点击解锁之后 跳转报告页面
    toReport() {
      ta.track('test_pay_click_pay', { report_id: this.uid, price: this.reportNotUnLockData.discountPrice })
      if (this.isLoading) return // 防止重复点击
      this.isDisabled = true
      this.isLoading = true
      api
        .payUnlockReportApi({
          reportId: 1,
        })
        .then((res) => {
          if (res.code == 200) {
            let { env, intentId, clientSecret, currency, orderId } = res.data
            let webUrlSuccess = this.webUrl + '/#/report?uid=' + this.uid + '&orderId=' + orderId + '&price=' + this.reportNotUnLockData.discountPrice
            let webUrlFail = this.webUrl + '/#/result?uid=' + this.uid + '&orderId=' + orderId + '&price=' + this.reportNotUnLockData.discountPrice
            let payments = initializeAirwallex()
            // console.log('payments', payments)
            payments.then((res) => {
              let result = res
              result.redirectToCheckout({
                mode: 'payment', //recurring-订阅 或 payment-支付
                env: env, //环境
                intent_id: intentId, //你的intent_id mode='payment'模式下必填
                client_secret: clientSecret, //你的client_secret 必填
                currency: currency, //你的货币符号 必填
                withBilling: true,
                requiredBillingContactFields: ['name', 'email', 'address'],
                locale: 'en',
                methods: ['card'],
                successUrl: webUrlSuccess, //支付成功后，重定向页面
                failUrl: webUrlFail, //支付失败后，重定向页面
              })
            })
          }
        })
        .catch((err) => {
          // console.log(err)
        })
        .finally(() => {
          this.isDisabled = false
          this.isLoading = false
        })
    },

    // 倒计时
    startCountdown() {
      // 清除可能存在的定时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
      }

      // 设置初始时间为5分钟
      this.minutes = 5
      this.seconds = 0

      // 创建定时器，每秒更新一次
      this.countdownTimer = setInterval(() => {
        // 如果秒数为0，需要减少分钟数
        if (this.seconds === 0) {
          // 如果分钟数也为0，表示倒计时结束
          if (this.minutes === 0) {
            clearInterval(this.countdownTimer)
            // 倒计时结束的处理逻辑，可以根据需要添加
            // console.log('倒计时结束')
            return
          }
          // 减少一分钟，秒数重置为59
          this.minutes--
          this.seconds = 59
        } else {
          // 减少一秒
          this.seconds--
        }
      }, 1000)
    },

    // 关闭支付失败弹窗
    closeFailDialog() {
      // 移除URL中的type参数，避免刷新页面时再次显示弹窗
      // 删除其他参数 需要保留uid

      if (history.pushState) {
        // 获取当前的uid参数值
        const currentUid = this.uid

        // 构建新的URL，只保留uid参数
        const newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?uid=' + currentUid

        window.history.pushState({ path: newurl }, '', newurl)
      }

      this.type = null
    },
  },
  mounted() {
    this.startCountdown()
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
}
</script>

<style scoped lang="scss">
.final-result-container {
  min-height: 100vh;
  background: linear-gradient(177deg, #e6e0f5 0%, #dee9f5 100%);
}
.isShowPay {
  padding: 12px 0px 0px;
}
.showPay {
  width: 100%;
  padding: 0 16px;
}

.loading-container {
  height: calc(100vh - 160px - 12px - 20px);
  padding: 26px 36px 0;
  width: 100%;
  background: url(../assets/images/obscure_bg.webp) no-repeat center center;
  background-size: cover;
  border-radius: 16px 16px 0 0;
  > .btn {
    width: 230px;
    height: 44px;
    margin: 27px auto 0;
    border-radius: 31px;
    background: #6f47ff;
    filter: blur(0px);
    box-shadow: 0px 1px 17px 0px rgba(135, 0, 210, 0.2042), inset 0px 1px 3px 0px rgba(255, 255, 255, 0.5);
    font-family: NotoSans;
    font-size: 15px;
    font-weight: 600;
    line-height: 44px;
    text-align: center;
    color: #ffffff;
    font-family: NotoSans-SemiBold;
    display: flex;
    justify-content: center;
    align-items: center;

    /* 加载圆圈动画 */
    .btn-loader-svg {
      width: 24px;
      height: 24px;
      animation: rotate 1s linear infinite;
      vertical-align: middle;
      margin-top: -2px; /* 微调垂直位置 */
    }

    .btn-loader-circle {
      stroke: white;
      stroke-linecap: round;
      stroke-dasharray: 60, 150;
      stroke-dashoffset: 0;
      animation: dash 1.5s ease-in-out infinite;
    }

    @keyframes rotate {
      100% {
        transform: rotate(360deg);
      }
    }

    @keyframes dash {
      0% {
        stroke-dasharray: 1, 150;
        stroke-dashoffset: 0;
      }
      50% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -35;
      }
      100% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -124;
      }
    }
  }
  .is-disabled {
    background: #a182f2;
    // cursor: not-allowed;
    opacity: 0.5;
    pointer-events: none;
  }
}
.pay {
  width: 302px;
  height: 332px;
  margin: 0 auto;
  position: relative;
  .pay-img {
    width: 100%;
    height: 100%;
    border-radius: 20px;
    box-shadow: 0px 0px 24px 0px rgba(57, 18, 200, 0.4);
  }
  .time {
    display: flex;
    align-items: center;
    position: absolute;
    top: 55px;
    right: 25px;
    font-size: 12px;
    color: #fe5615;
    > span {
      font-family: NotoSans;
      padding-right: 5px;
      font-weight: 600;
    }
    .time-box {
      width: 28px;
      height: 28px;
      background-color: #fe5615;
      color: #fff;
      text-align: center;
      line-height: 28px;
      font-size: 14px;
      border-radius: 6px;
      font-weight: 700;
      font-family: NotoSans-ExtraBold;
    }
    .gap {
      margin: 0 5px;
      font-weight: bold;
    }
  }
  .text {
    position: absolute;
    top: 126px;
    width: 100%;
    padding: 0 16px;
    font-family: NotoSans;
    font-size: 13px;
    text-align: center;
    color: #281e83;
  }
  .price {
    position: absolute;
    top: 220px;
    font-family: NotoSans;
    font-size: 12px;
    text-align: center;
    letter-spacing: normal;
    color: #a182f2;
  }
  .price1 {
    left: 31px;
  }
  .price2 {
    right: 31px;
  }
  .price-limit {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    font-family: NotoSans;
    font-size: 12px;
    text-align: center;
    .num {
      font-size: 24px;
      font-weight: 800;
      text-align: center;
      color: #6f47ff;
      font-family: NotoSans-ExtraBold;
    }
    .tip {
      font-size: 12px;
      text-align: center;
      color: #a182f2;
    }
  }
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #7b5cff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

/* 结果头部 - 渐变背景 */
.result-header-card {
  min-height: 150px;
  // max-width: 600px;
  // margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 16px;
  color: white;
  font-family: NotoSans;
  text-align: center;
  background: linear-gradient(115deg, #775ae0 0%, #f78295 100%), #ffffff;
  border-radius: 16px;
}

.result-title {
  font-size: 16px;
  font-weight: 700;
  font-weight: bold;
  font-family: NotoSans-ExtraBold;
}

.result-description {
  font-size: 14px;
  margin-top: 8px;
}

.result-description span {
  font-size: 24px;
  font-weight: bold;
  font-family: NotoSans-ExtraBold;
}

/* 支付失败弹窗样式 */
.payment-fail-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.dialog-content {
  width: 80%;
  max-width: 300px;
  background-color: #fff;
  border-radius: 12px;
  padding: 24px 16px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-message {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 24px;
  font-family: NotoSans-Medium;
}

.dialog-button {
  width: 80%;
  height: 44px;
  background: #6f47ff;
  color: white;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
  font-family: NotoSans-SemiBold;
  box-shadow: 0px 1px 10px rgba(135, 0, 210, 0.2);
}
</style>
